package com.issac.messagequeue.mqserver;

import com.issac.messagequeue.mqserver.common.*;
import com.issac.messagequeue.mqserver.coreclass.BasicProperties;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import javax.naming.ldap.SortKey;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 就是 消息队列 的本体服务器
 * 本质上是一个 TCP 服务器
 */
@Data
@Slf4j
public class BrokerServer {
    private ServerSocket serverSocket = null;

    // 当前考虑一个 BrokerServer 上只有一个虚拟主机
    private VirtualHost virtualHost = new VirtualHost("default");
    // 当前所有会话（有哪些客户端正在和服务器进行通信）
    // Key:channelId, Value:Socket
    private ConcurrentHashMap<String, Socket> sessions = new ConcurrentHashMap<>();
    // 线程池，处理多个客户端请求
    private ExecutorService executorService = null;
    // 控制服务器是否继续运行
    private volatile boolean runnable = true;

    public BrokerServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        log.info("[BrokerServer] 启动！");
        executorService = Executors.newCachedThreadPool();
        try {
            while (runnable) {
                Socket clientSocket = serverSocket.accept();
                // 处理连接的逻辑给线程池
                executorService.submit(() -> {
                    processConnection(clientSocket);
                });
            }
        } catch (SocketException e) {
            log.info("[BrokerServer] 服务器停止运行！");
        }
    }

    public void stop() throws IOException {
        runnable = false;
        executorService.shutdownNow();
        serverSocket.close();
    }

    /**
     * 通过这个方法：处理一个客户端连接
     * 在这个连接中会涉及很多请求&响应
     *
     * @param clientSocket
     */
    private void processConnection(Socket clientSocket) {
        try (InputStream inputStream = clientSocket.getInputStream();
             OutputStream outputStream = clientSocket.getOutputStream()) {
            try (DataInputStream dataInputStream = new DataInputStream(inputStream);
                 DataOutputStream dataOutputStream = new DataOutputStream(outputStream)) {
                while (true) {
                    // 1. 读取请求并解析
                    Request request = readRequest(dataInputStream);
                    // 2. 根据请求计算响应
                    Response response = process(request, clientSocket);
                    // 3. 把响应写回客户端
                    writeResponse(dataOutputStream, response);
                }
            }
        } catch (EOFException | SocketException e) {
            // 如果DataInputStream读到EOF会抛出异常
            log.info("[BrokerServer] connection 关闭！ 客户端地址： " + clientSocket.getInetAddress().toString()
                    + ": " + clientSocket.getPort());
        } catch (IOException | ClassNotFoundException | MqException e) {
            log.error("[BrokerServer] connection 出现异常！");
            e.printStackTrace();
        } finally {
            try {
                // 关闭当前socket
                clientSocket.close();
                // 清理：当前socket对应的channel
                clearClosedSession(clientSocket);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private Request readRequest(DataInputStream dataInputStream) throws IOException {
        Request request = new Request();
        request.setType(dataInputStream.readInt());
        request.setLength(dataInputStream.readInt());
        byte[] payload = new byte[request.getLength()];
        int n = dataInputStream.read(payload);
        if (n!=request.getLength()) {
            throw new IOException("[BrokerServer] 读取请求格式出错！");
        }
        request.setPayload(payload);
        return request;
    }

    private void writeResponse(DataOutputStream dataOutputStream, Response response) throws IOException {
        dataOutputStream.writeInt(response.getType());
        dataOutputStream.writeInt(response.getLength());
        dataOutputStream.write(response.getPayload());
        dataOutputStream.flush();
    }

    private Response process(Request request, Socket clientSocket) throws IOException, ClassNotFoundException, MqException {
        // 1. 把request中的payload作为一个初步的解析
        BasicArguments basicArguments = (BasicArguments) BinaryTool.fromBytes(request.getPayload());
        log.info("[BrokerServer] 正在解析请求Request： rid=" + basicArguments.getRid() + ", channelId=" + basicArguments.getChannelId()
                + ", type=" + request.getType() + ", length=" + request.getLength());

        // 2. 根据type的值进一步区分请求
        Boolean result = true;
        if (request.getType() == 0x1) {
            // 创建channel
            sessions.put(basicArguments.getChannelId(), clientSocket);
            log.info("[BrokerServer] 创建 channel 完成！ channelId=" + basicArguments.getChannelId());
        } else if (request.getType() == 0x2) {
            // 关闭channel
            sessions.remove(basicArguments.getChannelId());
            log.info("[BrokerServer] 删除 channel 完成！ channelId=" + basicArguments.getChannelId());
        } else if (request.getType() == 0x3) {
            // 创建exchange
            // 此时的payload就是ExcahngeDeclareArguments对象
            ExchangeDeclareArguments arguments = (ExchangeDeclareArguments) basicArguments;
            result = virtualHost.exchangeDeclare(arguments.getExchangeName(), arguments.getExchangeType(), arguments.isDurable(), arguments.isAutoDelete(), arguments.getArguments());
        } else if (request.getType() == 0x4) {
            // 销毁exchange
            ExchangeDeleteArguments arguments = (ExchangeDeleteArguments) basicArguments;
            result = virtualHost.exchangeDelete(arguments.getExchangeName());
        } else if (request.getType() == 0x5) {
            // 创建queue
            MsgQueueDeclareArguments arguments = (MsgQueueDeclareArguments) basicArguments;
            result = virtualHost.msgQueueDeclare(arguments.getMsgQueueName(), arguments.isDurable(), arguments.isExclusive(), arguments.isAutoDelete(), arguments.getArguments());
        } else if (request.getType() == 0x6) {
            // 销毁queue
            MsgQueueDeleteArguments arguments = (MsgQueueDeleteArguments) basicArguments;
            result = virtualHost.msgQueueDelete(arguments.getMsgQueueName());
        } else if (request.getType() == 0x7) {
            // 创建binding
            MsgQueueBindArguments arguments = (MsgQueueBindArguments) basicArguments;
            result = virtualHost.msgQueueBind(arguments.getMsgQueueName(), arguments.getExchangeName(), arguments.getBindingKey());
        } else if (request.getType() == 0x8) {
            // 销毁bind
            MsgQueueUnbindArguments arguments = (MsgQueueUnbindArguments) basicArguments;
            result = virtualHost.msgQueueUnbind(arguments.getMsgQueueName(), arguments.getExchangeName());
        } else if (request.getType() == 0x9) {
            // 发送message
            BasicPublishArguments arguments = (BasicPublishArguments) basicArguments;
            result = virtualHost.basicPublish(arguments.getExchangeName(), arguments.getRoutingKey(), arguments.getBasicProperties(), arguments.getBody());
        } else if (request.getType() == 0xa) {
            // 订阅message
            BasicConsumeArguments arguments = (BasicConsumeArguments) basicArguments;
            result = virtualHost.basicConsume(arguments.getConsumerTag(), arguments.getMsgQueueName(), arguments.isAutoAck(),
                    new Consumer() {
                        // 把服务器收到的消息直接推送回对应的消费者客户端
                        @Override
                        public void handleDelivery(String consumerTag, BasicProperties basicProperties, byte[] body) throws MqException, IOException {
                            // 1） 根据channelId找到socket对象
                            Socket clientSocket = sessions.get(consumerTag);
                            if (clientSocket == null || clientSocket.isClosed()) {
                                throw new MqException("[BrokerServer] 订阅消息的客户端已经关闭！");
                            }
                            // 2） 构造响应数据
                            SubscribeReturns subscribeReturns = new SubscribeReturns();
                            subscribeReturns.setChannelId(consumerTag);
                            subscribeReturns.setRid("");
                            subscribeReturns.setOk(true);
                            subscribeReturns.setConsumerTag(consumerTag);
                            subscribeReturns.setBasicProperties(basicProperties);
                            subscribeReturns.setBody(body);
                            // 序列化
                            byte[] payload = BinaryTool.toBytes(subscribeReturns);
                            // 构造响应
                            Response response = new Response();
                            response.setType(0xc);  // 表示：是服务器推送给客户端的消息
                            response.setLength(payload.length);
                            response.setPayload(payload);
                            // 3） 数据写回客户端
                            DataOutputStream dataOutputStream = new DataOutputStream(clientSocket.getOutputStream());
                            writeResponse(dataOutputStream, response);
                        }
                    });
        } else if (request.getType() == 0xb) {
            // 返回ack：调用basicAck确认消息
            BasicAckArguments arguments = (BasicAckArguments) basicArguments;
            result = virtualHost.basicAck(arguments.getMsgQueueName(), arguments.getMessageId());
        } else {
            // 当前type违法
            log.error("[BrokerServer] 当前 Type 不合法！ type=" + request.getType());
            throw new MqException("[BrokerServer] 未知的 Type！ type=" + request.getType());
        }
        // 3. 构造响应
        BasicReturns basicReturns = new BasicReturns();
        basicReturns.setChannelId(basicArguments.getChannelId());
        basicReturns.setRid(basicArguments.getRid());
        basicReturns.setOk(result);
        byte[] payload = BinaryTool.toBytes(basicReturns);
        Response response = new Response();
        response.setType(request.getType());
        response.setLength(payload.length);
        response.setPayload(payload);
        log.info("[BrokerServer] 响应Response构造成功！ rid=" + basicReturns.getRid() + ", channelId=" + basicReturns.getChannelId()
                + ", type=" + response.getType() + ", length=" + response.getLength());
        return response;
    }

    private void clearClosedSession(Socket clientSocket) {
        // 遍历 sessions 哈希表，把应该被关闭的 socket 对应的键值对删掉
        List<String> channelNeedToDelete = new ArrayList<>();
        for (Map.Entry<String, Socket> entry : sessions.entrySet()) {
            // 注意这里不能之间删除，添加和删除要分开操作
            if (entry.getValue() == clientSocket) {
                channelNeedToDelete.add(entry.getKey());
            }
        }
        // 删除
        for (String channelId : channelNeedToDelete) {
            sessions.remove(channelId);
        }
        log.info("[BrokerServer] 清理 sessions 完成！ 被清理的 channelId=" + channelNeedToDelete);
    }
}
